;$(function () {
    // 合同续费相关

    // 上传图片
    $(document).on('click', '.file-browser', function () {
        var file = $(this).closest('.file-group').find('[type="file"]');
        var fileID = file.attr('id');
        var showID = file.nextAll('.img-box').attr('id');
        file.on('click', function (e) {
            e.stopPropagation();
            uploadPreview({
                fileID,
                showID
            });
        }).on('change', function () {
            file.trigger('click');
        })
        file.trigger('click');
    });

    // 解决table中点击行选中与checkbox冲突问题
    $('table').on('load-success.bs.table', function (e,data) {
        $(e.target).find('label.lyear-checkbox').on('click', function (e) {
            rowsList = [];
            totalAmountData = 0;
            discountAmountData = 0;
            realAmountData = 0;
            receivablesData = 0;

            setTimeout(function () {
                $("#productListTable tbody  td input[type=text]").attr("disabled",false)
                $("#productListTable tbody .selected td input[type=text]").attr("disabled",true)

                rowsList = $('#productListTable').bootstrapTable('getSelections');

                //productDiscountPrice
                commitList(rowsList)
                for(let i=0,len=rowsList.length;i<len;i++){
                    if(rowsList[i].productDiscountPrice==''){
                        promptInfo('报价不能为空！', null, false);
                        return false;
                    }
                }
            },100)

            e.stopPropagation();
        })
    });

    /*
    * 功能：模态框关闭重置表单内容
    * */
    $('.modal').on('hidden.bs.modal', function () {
        $('#paymentMethod').selectpicker('val', '');
        $('#addProductModal input, #addProductModal textarea').val('');
        $('#addProductModal .surcharge-remarks, #addProductModal .approval').hide();
        $('.amount-total p').html('0');
    }).on('show.bs.modal', function () {
        $('#paymentMethod').selectpicker();
    });

    // 起止日期
    timeData('renenContractDate');

    // 初始化合作开发人员列表
    cooperateTable();
    // 初始化合作开发人员列表-分公司下拉菜单
    companiesList();
    $('#accountList').selectpicker();
    $('#paymentMethod').on('changed.bs.select', function () {
        console.log($(this).val())
        if ($(this).val() == 3) {
            // 余额支付重置并隐藏合作开发人员
            hideCooperate();
        } else if ($(this).val() == 2) {
            // 线下支付显示合作开发人员
            $('#cooperateWell').show();
        }
    });
});

/**
 * 功能：重置合作开发人员模块内容并隐藏
 * */
function hideCooperate() {
    var $cooperateWell = $('#cooperateWell');
    $cooperateWell.find('select').val('').selectpicker('refresh');
    $cooperateWell.find('select#accountList').prop('disabled', true).selectpicker('refresh');
    $('#cooperateTable').bootstrapTable('removeAll');
    $cooperateWell.hide();
}

/**
 * 功能：合作开发人员列表初始化
 * */
function cooperateTable() {
    $('#cooperateTable').bootstrapTable({
        class: 'table table-bordered table-hover table-striped',
        striped: true,                  // 是否显示行间隔色
        sortable: true,                 // 是否启用排序
        pagination: false,              // 是否显示分页
        minimumCountColumns: 2,         // 最少要显示的列数
        undefinedText: '-',             // cell没有值时显示
        uniqueId: 'userId',
        toolbar: '#cooperateTableToolbar',
        columns: [
            {title: '主键', field: 'userId', visible: false},
            {title: '主键', field: 'companyId', visible: false},
            {title: '合作开发人员姓名', field: 'userName', align: 'left', valign: 'middle'},
            {title: '分配金额', field: 'allocationMount',align: 'left', valign: 'middle',
                events: {
                    'change input': function (e, value, row, index) {
                        var inputValue = $($(e.target)[0]).val().replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g, '$1');
                        inputValue = Number(inputValue);
                        if (inputValue == 0) {
                            promptInfo('分配金额必须大于零，请重新输入！', function () {
                                $($(e.target)[0]).val('');
                            });
                            return;
                        }
                        $($(e.target)[0]).val(inputValue);
                        // 输入新值，先清空当前分配金额
                        row.allocationMount = '';
                        // 计算总计分配金额是否超过合同实际总金额
                        var flag = cooperateAmount(inputValue);
                        if (flag) {
                            // 未超过直接赋值
                            row.allocationMount = inputValue;
                        } else {
                            promptInfo('分配金额总和不能大于合同实际总金额，请重新输入！', function () {
                                $($(e.target)[0]).val('');
                                row.allocationMount = '';
                            });
                        }
                    }
                },
                formatter: function (value, row, index) {
                    var html = '<input type="text" class="form-control" value="' + (value || '') + '" id="allOcation-' + index + '" style="width: 200px;">';
                    return html;
                }
            },
            {title: '操作', field: 'couponDiscount', align: 'right', valign: 'middle', width: '120',
                formatter: function (value, row, index) {
                    var html = '<button type="button" class="btn btn-default btn-danger" onclick="removeRow(this, \'' + row.userId + '\')"><i class="mdi mdi-delete"></i>删除</button>';
                    return html;
                }
            },
        ],
        onPostBody: function (data) {
            // priceTotal();
            console.log(data)
        },
    });
}

/**
 * 功能：初始化分公司列表
 * 接口：罗杰
 * */
function companiesList() {
    $.ajax({
        url: '/sysCompany/selectCompanies',
        type: 'GET',
        dataType: "json",
        success: (function (data) {
            if (data.code == "000000") {
                var dataList = data.data;
                var selectOption = '';
                for (let i = 0; i < dataList.length; i++) {
                    selectOption += '<option value="' + dataList[i].companyId + '">' + dataList[i].companyName + '</option>';
                }
                $('#companiesList').selectpicker('destroy');
                $('#companiesList').html(selectOption).selectpicker({
                    size: 10
                });
            }
        }),
        error: (function (res) {
            $.alert({
                title: '错误提醒',
                content: '分公司列表数据请求失败'
            });
        })
    })
}

/**
 * 功能：根据所选分公司初始化人员列表
 * */
function getAccountList(element) {
    $('#addCooperateBtn').prop('disabled', true);

    var companyId = $(element).val();
    $.ajax({
        url: '/account/getAccountListByCompanyId',
        type: 'GET',
        dataType: "json",
        data: {
            companyId
        },
        success: (function (data) {
            if (data.code == "000000") {
                var dataList = data.data;
                var selectOption = '';
                for (let i = 0; i < dataList.length; i++) {
                    selectOption += '<option value="' + dataList[i].accountId + '">' + dataList[i].userName + '</option>';
                }
                $('#accountList').selectpicker('destroy').html(selectOption).prop('disabled', false).selectpicker({
                    size: 10
                }).one('changed.bs.select', function (event, clickedIndex, isSelected, previousValue) {
                    $('#addCooperateBtn').prop('disabled', false);
                })
            }
        }),
        error: (function (res) {
            $.alert({
                title: '错误提醒',
                content: '分公司人员数据请求失败'
            });
        })
    });
}

/**
 * 功能：新增合作开发人员
 * */
function addCooperate() {
    var companyId = $('#companiesList').val();
    var userId = $('#accountList').val();
    var userName = $('#accountList option:selected').html();

    var rowData = {
        companyId,              // 分公司Id
        userId,                 // 合作开发人员Id
        userName,               // 合作开发人员姓名
        allocationMount: ''     // 分配额度
    };

    var tableData = $('#cooperateTable').bootstrapTable('getData', true);

    if (tableData.length == 0) {
        // 直接插入
        $('#cooperateTable').bootstrapTable('append', rowData);
    } else {
        var flag = true;
        for (let i = 0; i < tableData.length; i++) {
            if (tableData[i].userId == userId) {
                flag = false;
                break;
            }
        }
        if (flag) {
            // 无重复，直接插入
            $('#cooperateTable').bootstrapTable('append', rowData);
        } else {
            // 提示有重复
            promptInfo('列表中已存在该联系人，不能重复添加！');
        }
    }
}

/**
 * 功能：分配金额计算，总计不能大于合同实际总金额
 * */
function cooperateAmount(amount) {
    // 输入值
    var amount = Number(amount);
    // 合同实际总金额
    var total = Number($('#renewRealAmount').html());
    // 合作开发人员列表数据
    var tableData = $('#cooperateTable').bootstrapTable('getData', true);
    var tableDataTotal = 0;
    for (let i = 0; i < tableData.length; i++) {
        tableDataTotal += Number(tableData[i].allocationMount);
    }
    console.log('输入值：' + amount, '表格内已有值：' + tableDataTotal, '输入的总值：' + (amount + tableDataTotal), '合同实际金额：' + total);
    if (tableDataTotal + amount > total) {
        return false;
    } else {
        return true;
    }
}

/**
 * 功能：删除行
 * 参数：fieldId - 删除行的目标列字段名称  value - 目标字段值
 * */
function removeRow(_this, fieldId) {
    $(_this).parents('table').bootstrapTable('removeByUniqueId', fieldId);
}

$('#renenSurcharge').on('change', function () {
    if ($(this).val() == '' || $(this).val() == '0') {
        $('.surcharge-remarks').hide();
    } else {
        $('.surcharge-remarks').show();
    }
    // priceTotal();
    // var $surchargeValue = parseFloat($('#surcharge').val()) || 0;


    rowsList = $('#productListTable').bootstrapTable('getSelections');
    totalAmountData=0,discountAmountData=0,realAmountData=0,receivablesData=0
    if(rowsList.length==0){

        $("#renewTotalAmount").html(totalAmountData)

        //    合同优惠总金额

        $("#renewDiscountAmount").html(discountAmountData)
        //    合同实际总金额 realAmount
        $("#renewRealAmount").html(realAmountData)
        //    应收款 receivables
        $("#renewReceivables").html(receivablesData)
    }
    for(let i=0,len=rowsList.length;i<len;i++){
        //    合同总金额 totalAmountData
        if(rowsList[i].productMemberPrice!=''){
            totalAmountData+=rowsList[i].productMemberPrice* rowsList[i].productNumber
        }else{
            totalAmountData+=0
        }
        $("#renewTotalAmount").html(totalAmountData)

        //    合同优惠总金额
        //    discountAmount
        if(rowsList[i].productDiscountPrice!=''){
            discountAmountData+=rowsList[i].productDiscountPrice* rowsList[i].productNumber
        }else{
            discountAmountData+=0
        }

        //    合同实际总金额 realAmount
        realAmountData=totalAmountData-discountAmountData

        $("#renewDiscountAmount").html(realAmountData)
        $("#renewRealAmount").html(discountAmountData)
        //    应收款 receivables
        receivablesData=totalAmountData-realAmountData+Number($("#renenSurcharge").val())
        $("#renewReceivables").html(receivablesData)
    }





})

/*弹框表格原价添加单选按钮*/
var rowsList;
var modalProductFormat = {
    // 产品价格
    priceChose: function (value, row, index, field) {
        if (value == null || value == undefined ) {
            return "-";
        }
        //productUnitPrice

        var type = row.chose || 'productMemberPrice';
        // var type = 'productMemberPrice';
        var html = '';
        if (field == type) {
            html += '<label class="lyear-radio radio-inline radio-primary"><input type="radio" data-target="' + field + '" name="price' + index + '" checked><span>' + value +'</span></label>';
        } else {
            html += '<label class="lyear-radio radio-inline radio-primary"><input type="radio" data-target="' + field + '" name="price' + index + '"><span>' + value +'</span></label>';
        }
        return html;
    },
    // 产品优惠后价格
    discountPrice: function (value, row, index, field) {
        // 优惠价为空 隐藏上传审批图片，否则显示

        // var discountPriceValue = value || '';
        var discountPriceValue;
        value == undefined ? discountPriceValue = '' : discountPriceValue = value;
        if (discountPriceValue != '') {
            discountPriceValue = parseFloat(discountPriceValue);
        }
        var inputId = 'productDiscountPrice' + index;
        var inputHtml = '<input type="text" value="' + discountPriceValue + '" placeholder="请输入" class="form-control" id="' + inputId + '">';
        row.productDiscountPrice = discountPriceValue || $(inputHtml).val();

        return inputHtml;
    },
    // 价格选择操作
    priceCategoryEvent: {
        'change input': function (e, value, row, index) {

            var inputNode = $(e.target)[0];
            row.chose = $(inputNode).data('target');
            modalProductFormat.priceChose(value, row);
            // 修改价格类型后，清空产品优惠后价格
            modalProductFormat.discountPrice('', row);
            modalProductFormat.total(value, row, index, 'productTotal');
            $('#productListTable').bootstrapTable('updateRow', {
                index,
                replace: true,
                row
            });
        }
    },

    // 产品数量
    number: function (value, row, index, field) {
        var numberValue = Number(value) || 1;
        var inputId = 'productNumber' + index;
        var inputHtml = '<input type="text" value="' + numberValue + '" placeholder="请输入" class="form-control" id="' + inputId + '">';
        row.productNumber = numberValue || $(inputHtml).val();

        return inputHtml;
    },
    // 总计
    total: function (value, row, index, field) {
        // 价格默认为产品单价
        // productMemberPrice productUnitPrice
        // var price = row.productMemberPrice;
        var price = row[row.chose] || row.productMemberPrice;
        var rowTotal = price * row.productNumber;
        row.productTotalPrice = rowTotal;

        return rowTotal;
    },
    // 产品优惠后价格
    discountPrice: function (value, row, index, field) {
        // 优惠价为空 隐藏上传审批图片，否则显示
        // value == '' ? $('.approval').hide(0) : $('.approval').show(0);
        // var discountPriceValue = value || '';
        var discountPriceValue;
        value == undefined ? discountPriceValue = '' : discountPriceValue = value;
        if (discountPriceValue != '') {
            discountPriceValue = parseFloat(discountPriceValue);
        }
        var inputId = 'productDiscountPrice' + index;
        var inputHtml = '<input type="text" value="' + discountPriceValue + '" placeholder="请输入" class="form-control" id="' + inputId + '">';
        row.productDiscountPrice = discountPriceValue || $(inputHtml).val();

        return inputHtml;
    },
    // 优惠后价格 自定义事件
    priceEvent: {
        'change input': function (e, value, row, index) {
            // console.log(e, value, row,9999)
            // $(e.target).val() == '' ? $('.approval').hide(0) : $('.approval').show(0);
            var newValue = activityPriceTest(e, value, row);
            console.log(newValue,'newValue',row)
            if (newValue == 'stop') return;

            modalProductFormat.discountPrice(newValue, row);

            $('#productActivityTable').bootstrapTable('updateRow', {
                index,
                replace: true,
                row
            });

            // e.stopPropagation();
        },
        'click input': function (e, value, row, index) {
            e.stopPropagation( )
        }
    },
    numberEvent: {
        'change input': function (e, value, row, index) {
            // 对数值进行判断
            var newValue = numberTest(e, value);
            if (newValue == 'stop') return;

            modalProductFormat.number(newValue, row);
            $('#productActivityTable').bootstrapTable('updateRow', {
                index,
                replace: true,
                row
            });
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    }
}

/****
 * 被选中check
 * */
var totalAmountData = 0,
    discountAmountData = 0,
    realAmountData = 0,
    receivablesData = 0,
    trueList1 = false,
    trueList2 = false;
$("#productListTable").on('click', function (e) {
    $("#productListTable tbody td input[type=text]").attr('disabled', false);
    $("#productListTable tbody .selected td input[type=text]").attr('disabled', true);

    rowsList = $('#productListTable').bootstrapTable('getSelections');

    totalAmountData = 0;
    discountAmountData = 0;
    realAmountData = 0;
    receivablesData = 0;

    commitList(rowsList)

    for(let i = 0; i < rowsList.length; i++){
        if(rowsList[i].productDiscountPrice == ''){
            console.log(rowsList[i].productDiscountPrice)
            promptInfo('报价不能为空', null, false);
            return false;
        }
    }

})

function commitList(rowsList) {
    if(rowsList.length==0){
        $('.approval').hide(0);

        $("#renewTotalAmount").html(totalAmountData)

        //    合同优惠总金额

        $("#renewDiscountAmount").html(discountAmountData)
        //    合同实际总金额 realAmount
        $("#renewRealAmount").html(realAmountData)
        //    应收款 receivables
        $("#renewReceivables").html(receivablesData)
    }
    var contantMoney=0;
    trueList1=false
    trueList2=false
    for(let i=0,len=rowsList.length;i<len;i++){
        //    合同总金额 totalAmountData
        totalAmountData+=rowsList[i].productMemberPrice* rowsList[i].productNumber
        contantMoney+=rowsList[i].productDiscountPrice* rowsList[i].productNumber
        if(rowsList[i].productDiscountPrice<rowsList[i].productMemberPrice){
            trueList1=true

        }else{
            trueList2=true
        }
    }
    if(trueList2==true && trueList1==false){
        $('.approval').hide(0);
    }else{

        $('.approval').show(0);
    }
    discountAmountData=totalAmountData-contantMoney
    setTimeout(function () {

        //合同总金额
        $("#renewTotalAmount").html(totalAmountData)
        //    合同优惠总金额  // 合同优惠总金额 = 合同总金额 - 产品计价总计 + 优惠券减免额度

        //合同优惠总金额
        if(discountAmountData<0){
            discountAmountData=0
        }
        $("#renewDiscountAmount").html(discountAmountData)
        //合同实际总金额
        $("#renewRealAmount").html(contantMoney)
        //应收款
        $("#renewReceivables").html(contantMoney+Number($("#renenSurcharge").val()))

    },100)
}
/**
 * 功能：活动产品列表价格判断
 * */
function activityPriceTest(e, preValue, row) {
    // 移除字符串的空格
    var newVal = $(e.target).val().replace(/\s/g,"");

    if (newVal == '') {
        return '';
    }
    if (newVal == preValue) {
        $(e.target).val(preValue);
        return 'stop';
    }
    if (isNaN(newVal) || newVal < 0) {
        promptInfo("请输入正确的价格！");
        $(e.target).val(preValue);
        return 'stop';
    } else {
        // 判断输入值是否高于活动原价
        if (parseFloat(newVal) > row.activityPrice) {
            promptInfo("活动优惠价不能高于活动原价，请重新输入！");
            $(e.target).val(preValue);
            return 'stop';
        }
    }
    return parseFloat(newVal).toFixed(2);
}


// 产品列表 - 添加产品弹窗列表
function initList(){
    $('#productListTable').bootstrapTable('destroy');
    // $('#productListTable').bootstrapTable('refresh');
    $('#productListTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        // url: '/customerContract/selectContractRenewalInformation?contractId='+contractId,//请求地址
        url:"/customerMemberProduct/selectContractMemberProductList",
        // method: 'get',//请求方式
        method: 'post',//请求方式
        // contentType: "application/x-www-form-urlencoded",//请求内容类型
        contentType:"application/json;charset=utf-8",
        dataType: "json",                   // 数据类型
        striped: true,                      // 是否显示行间隔色
        sortable: true,                     // 是否启用排序
        sortOrder: "desc",                  // 排序方式
        sortName: 'createTm',               // 排序字段
        cache: false,                       // 是否使用缓存
        showColumns: false,                 // 显示隐藏列
        showRefresh: false,                 // 显示刷新按钮
        showToggle: false,                  // 切换显示样式
        showFooter: false,                  // 显示Table脚部
        pagination: true,                   // 是否显示分页
        showPaginationSwitch: false,        // 是否显示分页按钮
        clickToSelect: true,                // 是否启用点击选中行
        maintainSelected: true,             // 分页是否保留选中
        singleSelect: false,
        minimumCountColumns: 2,             // 最少要显示的列数
        undefinedText: '-',                  // cell没有值时显示
        sidePagination: "server",           // 分页方式：client客户端分页，server服务端分页
        // serverSort: true,
        uniqueId: 'customerProductId',
        idField: 'customerProductId',
        pageSize: 9999,                        // 每页的记录行数
        pageNumber: 1,                      // 初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",        // 可供选择的每页的行数

        queryParams: dataContract,//查询参数
        columns: [

            {title: '主键', field: 'customerProductId', visible: false},
            {checkbox: true, visible: true},
            {title: '产品名称', field: 'productName', align: 'left', valign: 'middle'},
            {title: '产品类别', field: 'productCategories', align: 'left', valign: 'middle',visible: false},
            {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
            {title: '产品单价', field: 'productUnitPrice', align: 'left', valign: 'middle'},
            {title: '产品会员价', field: 'productMemberPrice', align: 'left', valign: 'middle'},
            {title: '当前报价', field: 'productDiscountPrice', align: 'left', valign: 'middle', width: '160', events: modalProductFormat.priceEvent, formatter: modalProductFormat.discountPrice},
            {title: '产品数量', field: 'productNumber', align: 'left', valign: 'middle', width: '160', events: modalProductFormat.numberEvent, formatter: modalProductFormat.number},
            // {title: '操作', field: 'productOperation', align: 'right', valign: 'middle', width: '100', formatter: productFormat.operation},
            {title: '产品编码', field: 'productCode', visible: false},
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    // "rows": result.data.productEditArr.list,
                    // "total": result.data.productEditArr.totalRecords//总条数
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };

                // getCustomerContactPersonSelect(result.data.contactId);


            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                // alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}
// 产品列表 - 添加产品弹窗列表
function dataContract(params) {
    var data={
        pageSize: params.limit,                         //页面大小
        pageIndex: (params.offset / params.limit) + 1,   //页码
        sortName: params.sort,      //排序列名
        sortOrder: params.order, //排位命令（desc，asc）
        productCategories: 2, // 会员类型
        whetherRenew : '0'
    }
    return JSON.stringify(data)
}

function initFollowRecord(customerId){
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: '/clueFollow/selectClueFollowListByCustomerId?customerId=' + customerId,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '';
                $.each(data.data, function(n, value) {
                    /*                    if(contract != null && contract.followRecordId == value.clueFollowId){
                                            html += '<option value="' + value.clueFollowId + '" selected>' + value.followWayName + ' ' + value.followTm + '</option>';
                                        }else {*/
                    html += '<option value="' + value.clueFollowId + '">' + value.followWayName + ' ' + value.followTm + '</option>';
                    /*                    }*/
                });
                $('#followRecordList').selectpicker('destroy').html(html).attr('disabled', false).selectpicker('refresh');
            } else {
                alert("跟进记录下拉框-请求失败");
            }
        }),
        error: (function (res) {
            alert("跟进记录下拉框-请求失败");
        })
    });
}

function initOpportunity(customerId){
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: '/opportunity/selectOpportunityListByCustomerId?customerId=' + customerId,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '';
                $.each(data.data, function(n, value) {
                    /*                    if(contract!=null&&contract.opportunityId == value.opportunityId){
                                            html += '<option value="' + value.opportunityId + '" selected>' + value.opportunityTitle + '</option>';
                                        }else {*/
                    html += '<option value="' + value.opportunityId + '">' + value.opportunityTitle + '</option>';
                    /*                    }*/
                });

                $('#opportunityList').selectpicker('destroy').html(html).attr('disabled', false).selectpicker('refresh');

            } else {
                alert("赢单商机下拉框-请求失败");
            }
        }),
        error: (function (res) {
            alert("赢单商机下拉框-请求失败");
        })
    });
}

/**
 * 合同续费保存功能
 */
function addRenewContract(){

    //客户id
    var customerId = "";
    //客户名称
    var customerName = "";
    //客户类型
    var customerType = "";
    //客户邮箱
    var customerEmail = "";
    /*    //跟进记录id
        var followRecordId = "";
        //商机id
        var opportunityId = "";
        //合作开发人员id
        var coDeveloperList = [];
        //是否保密
        var whetherKeepSecret = "";*/
    //合同原来起始时间
    var contractOldStartDate = "";
    //合同原来结束时间
    var contractOldEndDate = "";

    $.ajax({
        type: 'GET',
        async:false,
        dataType: "json",
        url: '/customerContract/selectContractById?contractId=' + contractId,
        success: (function (data) {
            if (data.code == "000000") {
                customerId = data.data.customerId;
                customerName = data.data.customerName;
                customerType = data.data.customerType;
                customerEmail = data.data.customerEmail;
                //followRecordId = data.data.followRecordId;
                //opportunityId = data.data.opportunityId;
                //coDeveloperList = data.data.coDeveloperList;
                //whetherKeepSecret = data.data.whetherKeepSecret;
                contractOldStartDate = data.data.contractStartDate;
                contractOldEndDate = data.data.contractEndDate;
            } else {
                alert("获取合同信息请求失败");
            }
        }),
        error: (function (res) {
            alert("获取合同信息请求失败");
        })
    });

    //联系人id
    // var contactId=$("#customerContractList").val();
    var contactId = '';
    //联系人名称
    var contactName = $.trim($('#customerContractName').val());
    //联系方式
    var contactDetails = $.trim($('#customerContactInformation').val());
    //会员主合同
    var masterMembershipContract = contractId;
    //合同起止日期
    var contractPeriodValidity = $("#renenContractDate").val().split('至');
    // 起止时间-开始时间
    var contractNewStartDate = $.trim(contractPeriodValidity[0]);
    // 起止时间-结束时间
    var contractNewEndDate = $.trim(contractPeriodValidity[1]);
    //付款账号
    //var paymentAccount = $('#paymentAccount').val();
    //支付方式
    var paymentMethod = $('#paymentMethod').val();
    //附加费用
    //金额
    var orderSurcharge = $('#renenSurcharge').val();
    //备注
    var orderSurchargeRemark = $('#renenOrderSurchargeRemark').val();
    //是否申请电子合同
    //var applyElectronicContract = $("input[name='apply']:checked").val();


    //合同实际总金额
    var contractActualTotalAmount = $("#renewRealAmount").text();
    //合同优惠总金额
    var contractDiscountTotalAmount = $("#renewDiscountAmount").text();
    //合同 总金额
    var contractTotalAmount = $("#renewTotalAmount").text();
    //应收款
    var contractReceivables= $("#renewReceivables").text();

    // 上传审核图片
    /*    var examineFile = $('#examineImg');

        // 合同优惠时，必须上传审核图片
        if(contractDiscountTotalAmount != 0 && !$('#examinedPic').val()){
            if (examineFile.val()) {
                uploadImg(examineFile);
            } else {
                promptInfo("审核为必填项!");
                return;
            }
        }
    */

    //关联跟进记录
    var followRecordId = $('#followRecordList').val();
    //关联赢单商机
    var opportunityId = $('#opportunityList').val();

    //合同附件
    var contractAnnexId = $('#contractPic').val();
    //合同审核
    var reviewAnnexId = $('#examinedPic').val();

    //审核备注
    var contractReviewNotes = $('#renewContractReviewNotes').val();

    // 续费列表数据
    //获取选中行的数据
    var productData = $('#productListTable').bootstrapTable('getSelections');
    // var productData = $('#productListTable').bootstrapTable('getData', true);        // 产品列表数据
    var productArr = [];                                                            // 产品列表数组
    for (var i = 0; i < productData.length; i++) {
        if(productData[i].productDiscountPrice==''){
            promptInfo("当前报价不能为空!");
            return;
        }
        var rowData = {
            productId: productData[i].customerProductId,                            // 产品id
            productName: productData[i].productName,                                // 产品名称
            productCategories: productData[i].productCategories,                    // 产品分类--0:非会员;1:会员；
            productOriginalPrice: productData[i].productOriginalPrice,              // 原价
            productUnitPrice: productData[i].productUnitPrice,                      // 单价
            productMemberPrice: productData[i].productMemberPrice,                  // 会员价
            productFinalPrice: productData[i].productDiscountPrice,                 // 成交价
            productTotalPrice: productData[i].productTotalPrice,                    // 总计价格
            productQuantity: productData[i].productNumber,                          // 数量
            productCode:productData[i].productCode,                                 // 产品编码
        }
        productArr.push(rowData);
    }

    //合作开发人员
    var coDeveloperList = $('#cooperateTable').bootstrapTable('getData', true);


    //产品判空提示
    if(productArr.length==0){
        promptInfo("产品不能为空!");
        return;
    }

    if (orderSurcharge > 0 && orderSurchargeRemark == '') {
        promptInfo('请填写附加费用备注信息！');
        return;
    }


    //客户联系人判空提示
    if (!contactName) {
        promptInfo("客户联系人不能为空!");
        return;
    }

    //联系方式判空提示
    /*if (!contactDetails) {
        promptInfo("联系方式不能为空!");
        return;
    }*/

    // 联系方式判断
    var contactInformationReg = /^(\d{1,20})$/;
    var contactInformationPattern = new RegExp(contactInformationReg);
    if(!contactDetails){
        promptInfo("联系方式不能为空！");
        return;
    }else{
        if(!contactInformationPattern.test(contactDetails)) {
            promptInfo("请输入正确的手机号");
            return;
        }
    }




    //客户邮箱判空提示
    // if (!customerEmail) {
    //     promptInfo("客户邮箱不能为空!");
    //     return;
    // }

    //合同起止日期判空提示
    if (!contractNewStartDate) {
        promptInfo("合同起止日期不能为空!");
        return;
    }

    //支付方式判空提示
    if (!paymentMethod) {
        promptInfo("支付方式不能为空!");
        return;
    }

    // 合同附件判空提示
    /*if (!contractAnnexId) {
        // 上传合同附件
        var contractFile = $('#contractImg');
        // 合同附件不为空上传图片并返回图片id
        if (contractFile.val()) {
            contractAnnexId = uploadImg(contractFile);
        } else {
            promptInfo("合同附件必须上传!");
            return;
        }
    }*/

    //商机判空提示
    if (!opportunityId) {
        promptInfo("关联赢单商机必选!");
        return;
    }

    //跟进记录判空提示
    if (!followRecordId) {
        promptInfo("跟进记录必选!");
        return;
    }

    // 审核附件判空提示
    if(contractDiscountTotalAmount>0&&!reviewAnnexId){
        promptInfo("审核附件必须上传!");
        return;
    }

    //审核备注判空提示
    /*if(contractDiscountTotalAmount!=0&&!contractReviewNotes){
        promptInfo("审核备注必填!");
        return;
    }*/

    // 验证合作开发人员分配金额
    for (let i = 0; i < coDeveloperList.length; i++) {
        if (coDeveloperList[i].allocationMount == '') {
            $.alert({
                title: '温馨提示',
                content: '合作开发人员分配金额不能为空，请输入！',
                scrollToPreviousElement: false,
                scrollToPreviousElementAnimate: false,
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'btn-primary',
                        action: function () {
                            // e.preventDefault();
                            $('#allOcation-' + i).focus();
                            return;
                        }
                    }
                }
            });
            return;
        }
    }

    var jsonData = {
        "contractType":'4',
        "customerId":customerId,
        "customerName":customerName,
        "customerType":customerType,
        "contactId":contactId,
        "contactName":contactName,
        "contactDetails":contactDetails,
        "customerEmail":customerEmail,
        "masterMembershipContract":masterMembershipContract,
        "contractNewStartDate":contractNewStartDate,
        "contractNewEndDate":contractNewEndDate,
        //"paymentAccount":paymentAccount,
        "paymentMethod":paymentMethod,
        "followRecordId":followRecordId,
        "opportunityId":opportunityId,
        //"applyElectronicContract":applyElectronicContract,
        //"whetherKeepSecret":whetherKeepSecret,
        "contractOldStartDate":contractOldStartDate,
        "contractOldEndDate":contractOldEndDate,
        "contractTotalAmount":contractTotalAmount,
        "contractDiscountTotalAmount":contractDiscountTotalAmount,
        "contractActualTotalAmount":contractActualTotalAmount,
        "contractReceivables":contractReceivables,
        "contractReviewNotes":contractReviewNotes,
        //附加费用
        "orderSurcharge":orderSurcharge,
        "orderSurchargeRemark":orderSurchargeRemark,
        "contractAnnexId":contractAnnexId,
        "reviewAnnexId":reviewAnnexId,
        "customerContractProductAddQOList":productArr,
        "coDeveloperList":coDeveloperList,
    }
    console.log(jsonData)

    $.ajax({
        url: '/customerContract/addContractInformation',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if(data.code == '000000'){
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            scrollToPreviousElement: false,
                            scrollToPreviousElementAnimate: false,
                            action: function () {
                                //刷新列表
                                $('#contractDetail').bootstrapTable('refresh');
                                //关闭弹框
                                $('#addProductModal').modal('hide');
                            }
                        }
                    }
                });
            } else if(data.code == 'CV0001'){
                //合同不能编辑
                $.alert(data.message);
            } else if(data.code == 'CV0002'){
                //没有会员产品合同不能保存
                $.alert(data.message);
            }else {
                $.alert("保存失败");
            }
        }),
        error: (function (res) {
            $.alert("保存失败");
        })
    })
}